package com.bym.mall.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.bym.mall.consts.MallConst;
import com.bym.mall.exception.UserLoginException;
import com.bym.mall.utils.UserUtil;
import com.bym.mall.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户登录拦截器
 *
 * @author My
 * @date 2022/03/23
 */
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {

    /**
     * 在后端接口被访问前进行处理
     * true表示流程继续，false表示流程结束
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("UserLoginInterceptor.preHandle");

        HttpSession httpSession = request.getSession();
        UserVo userVo = (UserVo) httpSession.getAttribute(MallConst.CURRENT_USER);

        if (ObjectUtil.isNull(userVo)) {
            //用户没有登录，进行拦截
            throw new UserLoginException();
        }

        //将当前user添加至ThreadLocal
        UserUtil.addUser(userVo);

        //用户已经登录，放行
        return true;
    }

    /**
     * 在请求结束时处理
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @param ex       前女友
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从ThreadLocal中删除当前user（防止内存泄露）
        UserUtil.removeUser();
    }
}
